import { defineStore } from "pinia"
import { computed, ref } from "vue"
import { insertCartAPI, findNewCartListAPI, delCartAPI } from '@/api'
import { useUserStore } from './user'

export const useCartStore = defineStore('cart', () => {
  const cartList = ref([])
  const userStore = useUserStore()
  // 是否登录
  const isLogin = computed(() => userStore.userInfo.token)
  // 获取最新购物车
  const getNewCartList = async () => {
    const res = await findNewCartListAPI()
    cartList.value = res.result
  }
  // 添加购物车
  const addCart = async (sku) => {
    if (isLogin.value) {
      const { skuId, count } = sku
      await insertCartAPI({ skuId, count })
      getNewCartList()
    } else {
      // 已添加过 count+1
      // 没添加过直接push
      const isSku = cartList.value.find(item => item.skuId === sku.skuId)
      if (isSku) {
        isSku.count++
      } else {
        cartList.value.push(sku)
      }
    }
  }
  // 删除购物车
  const delCart = async (skuId) => {
    if (isLogin.value) {
      await delCartAPI([skuId])
      getNewCartList()
    } else {
      const delIndex = cartList.value.findIndex(item => item.skuId === skuId)
      cartList.value.splice(delIndex, 1)
    }
  }
  // 清除购物车
  const clearCart = () => {
    cartList.value = []
  }
  // 全选
  const allCheck = (select) => {
    cartList.value.forEach(item => item.selected = select)
  }

  // 计算属性
  // 总数量
  const totalNum = computed(() => cartList.value.reduce((a, b) => a + b.count, 0))
  // 总价钱
  const totalPrice = computed(() => cartList.value.reduce((a, b) => a + b.price * b.count, 0))
  // 选择的总数
  const selectNum = computed(() =>
    cartList.value.filter(item => item.selected)
      .reduce((a, b) => a + b.count, 0)
  )
  // 选择的总价钱
  const selectPrice = computed(() =>
    cartList.value.filter(item => item.selected)
      .reduce((a, b) => a + b.count * b.price, 0)
  )
  // 是否全选
  const isAll = computed(() => cartList.value.every(item => item.selected))

  return {
    cartList,
    totalNum,
    totalPrice,
    selectNum,
    selectPrice,
    addCart,
    delCart,
    clearCart,
    allCheck,
    isAll,
    getNewCartList
  }
}, {
  persist: true
})